#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QMenuBar>
#include<QMenu>
#include<QAction>
#include<QTextEdit>
#include<QFileDialog>
#include<QDebug>
#include<fstream>
#include<QString>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("我的记事本");
    QMenuBar* bar = new QMenuBar(this);
    this->setMenuBar(bar);
    QMenu* m1 = new QMenu("文件");
    bar->addMenu(m1);
    QAction* act1 = new QAction("保存");
    QAction* act2 = new QAction("加载");
    m1->addAction(act1);
    m1->addSeparator();
    m1->addAction(act2);
    //创建中央控件
    QTextEdit* edit = new QTextEdit(this);
    this->setCentralWidget(edit);
    edit->setPlaceholderText("此处编写文本内容..");
    connect(act1,&QAction::triggered,this,[=]()
    {
        QFileDialog* saveFile = new QFileDialog(this);
        QString path = saveFile->getSaveFileName(this,"保存文件","./");
        qDebug()<<"file path = "<<path;
        std::ofstream out(path.toStdString());
        if(!out.is_open())
        {
            qDebug()<<"打开文件失败，路径:"<<path;
            return;
        }
        QString data = edit->toPlainText();
        out<<data.toStdString();
        out.close();

    });
    connect(act2,&QAction::triggered,this,[=]()
    {
        QFileDialog* openFile = new QFileDialog(this);
        QString path = openFile->getOpenFileName(this,"打开文件","./Open/");
        std::ifstream in(path.toStdString());
        if(!in.is_open())
        {
            qDebug()<<"打开文件失败，路径:"<<path;
            return;
        }
        std::string line;
        std::string total;
        while(std::getline(in,line))
        {
            line+="\n";
            total += line;
        }
        QString data = QString::fromStdString(total);
        edit->setText(data);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

